package cn.zhiquxing.lock.master_worker;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class Worker<T extends Task, R> {
    //接受任务的阻塞队列
    private LinkedBlockingQueue<T> taskQueue = new LinkedBlockingQueue<>();
    // worker的编号
    static AtomicInteger index = new AtomicInteger(1);

    private int workerId;

    Thread thread = null;

    public Worker() {
        this.workerId = index.getAndIncrement();
        thread =new Thread(() -> this.run());
        thread.start();
    }
    
    public void run() {
        for(;;) {
            try {
                T task = this.taskQueue.take();
                task.setWorkerId(this.workerId);
                task.execute();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    // 接收任务到异步队列
    public void submit(T task, Consumer<R> action) {
        task.resultAction = action;
        try {
            this.taskQueue.put(task);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
